<?php

namespace app\middleware;

use app\common\JwpLog;
use app\manager\RedisInstance;
use app\model\RegisterModel;
use app\model\UserModel;
use app\util\UserContext;
use think\facade\Request;



/**todo
 * 统一返回格式分装
 * 新增拦截器完成统一异常捕获
 * */
class CheckToken1
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $cookie = $_COOKIE;
        $urls = config("app.nologin_url");

        $startTime = microtime(true);
        try {
            if (in_array(Request::url(),$urls)){
                return $next($request);
            } else {
                if (empty($cookie['token'])) {
                    return redirect('/user/login');
                }
                $uid = RedisInstance::get($cookie['token']);
                $user = UserModel::seletUserById($uid);
                if (!empty($ris)){
                    UserContext::set($user);
                    return $next($request);
                } else {
                    return redirect('/user/login');
                }
            }
        } finally {
            $endTime = microtime(true);
            $cost = ($endTime - $startTime)*1000;
            JwpLog::info(sprintf("cost[%d] token[%s] param[%s] data[%s]",$cost, $cookie['token']??"", json_encode($_GET), json_encode($_POST)));
        }
    }
}
